import service from '@/api/axios'

// 下载文件为二进制 Blob（全量下载，POST）
export async function downloadFileBlobApi(fileId: string) {
  const resp = await service.request<Blob>({
    url: `/file/download/${encodeURIComponent(fileId)}`,
    method: 'POST',
    responseType: 'blob',
    data: { fileId }
  })
  return resp.data
}

// 获取下载元信息（POST meta）
export async function getFileMetaApi(fileId: string): Promise<{
  totalSize: number | null
  acceptRanges: boolean
  contentType?: string
  fileNameFromDisposition?: string
}> {
  console.log('getFileMetaApi fileId:', fileId)
  try {
    const metaResp = await service.request({
      url: `/file/download/meta`,
      method: 'POST',
      data: { fileId }
    })
    const headers: any = metaResp.headers || {}
    const payload: any = metaResp.data || {}
    const len = Number(payload.totalSize ?? payload.size ?? headers['content-length'] ?? headers['Content-Length'])
    const acceptRanges = Boolean(payload.acceptRanges ?? payload.range ?? false)
    const contentType = payload.contentType || headers['content-type'] || headers['Content-Type']
    const fileNameFromDisposition = payload.fileName || payload.filename || undefined
    return { totalSize: Number.isFinite(len) ? len : null, acceptRanges, contentType, fileNameFromDisposition }
  } catch {
    return { totalSize: null, acceptRanges: false }
  }
}

// 分片范围下载（POST + X-Range），endExclusive 不包含
export async function downloadFileRangeApi(params: {
  fileId: string
  start: number
  endExclusive: number
  signal?: AbortSignal
  onProgress?: (evt: ProgressEvent) => void
}): Promise<{ data: ArrayBuffer; contentType?: string }>
{
  const { fileId, start, endExclusive, signal, onProgress } = params
  const endInclusive = Math.max(start, endExclusive - 1)
  console.log('downloadFileRangeApi params:', { fileId, start, endInclusive })
  const resp = await service.request<ArrayBuffer>({
    url: `/file/download/${encodeURIComponent(fileId)}/download-range`,
    method: 'POST',
    responseType: 'arraybuffer',
    data: { fileId, start, end: endInclusive },
    headers: { 'X-Range': `bytes=${start}-${endInclusive}` },
    onDownloadProgress: onProgress as any,
    signal,
  })
  const contentType = (resp.headers as any)['content-type'] ?? (resp.headers as any)['Content-Type']
  return { data: resp.data, contentType }
}
